import md5 from 'js-md5'

/** 时间格式化处理 **/
export function dateFormat (date, fmt) {
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    'S': date.getMilliseconds()
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return fmt
}

/**
 * 获取 本周本月本季度本年时间段
 * @param val
 * @returns Date[]
 */
export function timeSlot (val){
  let startTime, endTime;
  let now = new Date(); //当前日期
  let nowDayOfWeek = now.getDay(); //今天本周的第几天
  let nowDay = now.getDate(); //当前日
  let nowMonth = now.getMonth(); //当前月
  let nowYear = now.getFullYear(); //当前年
  let jd=Math.ceil((nowMonth + 1) / 3)
  switch (val) {
    case "day":
      startTime = new Date()
      endTime = new Date();
      break;
    case "yesterday":
      startTime = new Date(new Date().getTime()-24*3600*1000)
      endTime = new Date(new Date().getTime()-24*3600*1000)
      break;
    case "week":
      // 调整为周日为最后一天模式...
      startTime = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek +1)
      endTime = new Date(nowYear, nowMonth, nowDay + 6 - nowDayOfWeek + 1)
      break;
    case "month":
      startTime = new Date(nowYear, nowMonth, 1)
      endTime = new Date(nowYear, nowMonth + 1, 0)
      break;
    case "lastMonth":
      startTime = new Date(nowYear,nowMonth-1,1)
      endTime = new Date(nowYear,nowMonth,0)
      break;
    case "quarter":
      // console.log(jd,'jd')
      startTime = new Date(nowYear, (jd-1)*3, 1)
      endTime = new Date(nowYear, jd*3, 0)
      break;
    case "year":
      startTime = new Date(nowYear, 0, 1)
      endTime = new Date(nowYear, 11, 31)
      break
  }
  // console.log('startTime:',startTime)
  // console.log('endTime:',endTime)
  return [startTime, endTime]
}


/**
 * 获取上个月今日
 */
export function getLastMonthDay() {
  let now = new Date();
  // 获取在当月哪天  比如8号
  let day = now.getDate();
  console.log("now:"+dateFormat(now,'yyyy-MM-dd hh:mm:ss'));
  console.log("day:"+ day);
  // 比如8号  减去8天  多减去一秒
  let timeStamp  = now.getTime()-(day*24*3600*1000)-1000;
  return new Date(timeStamp);
}

/**
 * 获取一个时间的当月开始时间与结束时间
 * @param date
 * @returns {Date[]}
 */
export function getMonthStarEnd(date) {
  let nowMonth = date.getMonth(); //当前月
  let nowYear = date.getFullYear(); //当前年
  let startTime = new Date(nowYear,nowMonth,1)
  let endTime = new Date(nowYear,nowMonth + 1,0)
  return [startTime, endTime]
}
/**
 * 添加千位符
 * @param num
 * @returns {string}
 */
export function numFormat(num){
  if(num===0||!num){
    return '0.00'
  }
  num=num.toString().split(".");  // 分隔小数点
  let arr=num[0].split("").reverse();  // 转换成字符数组并且倒序排列

  // 符号位处理  如果有-号 3位时不加千分位符号
  let f = '';
  if(arr[arr.length-1]==='-'){
    f = '-'
    // 删除掉负号
    arr.splice(arr.length-1,1)
  }

  let res=[];

  for(let i=0,len=arr.length;i<len;i++){
    if(i%3===0&&i!==0){
      res.push(",");   // 添加分隔符
    }
    res.push(arr[i]);
  }
  // 如果符号位存在 添加上符号位
  if(f){
    res.push(f)
  }

  res.reverse(); // 再次倒序成为正确的顺序
  if(num[1]){  // 如果有小数的话添加小数部分
    res=res.join("").concat("."+num[1]);
  }else{
    res=res.join("");
  }
  return res;
}

/***
 * 根据时间生成唯一uuid
 **/
export function uuid (date) {
  // 固定下时间
  date = date || new Date()
  // 随机长度5+时间长度17 22
  let len = 5
  let uuid = ''
  let $chars = 'ABCDEFGHJKLMNOPQRSTUVWXYZ1234567890'
  let maxPos = $chars.length
  for (let i = 0; i < len; i++) {
    uuid += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  uuid += dateFormat(date, 'yyyyMMddhhmmssS')
  return uuid
}



export function parseTime (time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return timeStr
}
// 格式化时间
export function getQueryObject (url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 *get getByteLen
 * @param {Sting} val input value
 * @returns {number} output value
 */
export function getByteLen (val) {
  let len = 0
  for (let i = 0; i < val.length; i++) {
    // eslint-disable-next-line no-control-regex
    if (val[i].match(/[^\x00-\xff]/ig) != null) {
      len += 1
    } else {
      len += 0.5
    }
  }
  return Math.floor(len)
}

export function cleanArray (actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

export function param (json) {
  if (!json) return ''
  return cleanArray(Object.keys(json).map(key => {
    if (json[key] === undefined) return ''
    return encodeURIComponent(key) + '=' +
      encodeURIComponent(json[key])
  })).join('&')
}

export function param2Obj (url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
}

export function html2Text (val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

export function objectMerge (target, source) {
  /* Merges two  objects,
   giving the last one precedence */

  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  for (const property in source) {
    if (source.hasOwnProperty(property)) {
      const sourceProperty = source[property]
      if (typeof sourceProperty === 'object') {
        target[property] = objectMerge(target[property], sourceProperty)
        continue
      }
      target[property] = sourceProperty
    }
  }
  return target
}

export function scrollTo (element, to, duration) {
  if (duration <= 0) return
  const difference = to - element.scrollTop
  const perTick = difference / duration * 10
  setTimeout(() => {
    console.log(new Date())
    element.scrollTop = element.scrollTop + perTick
    if (element.scrollTop === to) return
    scrollTo(element, to, duration - 10)
  }, 10)
}

export function toggleClass (element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString = classString.substr(0, nameIndex) + classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

export const pickerOptions = [
  {
    text: '今天',
    onClick (picker) {
      const end = new Date()
      const start = new Date(new Date().toDateString())
      end.setTime(start.getTime())
      picker.$emit('pick', [start, end])
    }
  }, {
    text: '最近一周',
    onClick (picker) {
      const end = new Date(new Date().toDateString())
      const start = new Date()
      start.setTime(end.getTime() - 3600 * 1000 * 24 * 7)
      picker.$emit('pick', [start, end])
    }
  }, {
    text: '最近一个月',
    onClick (picker) {
      const end = new Date(new Date().toDateString())
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      picker.$emit('pick', [start, end])
    }
  }, {
    text: '最近三个月',
    onClick (picker) {
      const end = new Date(new Date().toDateString())
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      picker.$emit('pick', [start, end])
    }
  }]

/**
 * 获取周时间
 * @param dateValue
 * @param next
 * @returns {Date[]}
 */
export function getWeekDate(dateValue,next) {
  let date
  let beginDate;
  let endDate;
  if (dateValue instanceof Date) {
    date = dateValue;
  } else {
    date = new Date(dateValue);
  }
  let subDay;
  let weekDay = date.getDay();
  if (weekDay === 0) {
    //周天
    subDay = 6;
  } else {
    subDay = weekDay - 1;
  }
  let beginDateTime = date.getTime() - (86400000 * subDay);

  let addDay;
  if (weekDay === 0) {
    //周天
    addDay = 0;
  }else{
    addDay= 7 - weekDay
  }
  let endDateTime = date.getTime() + (86400000 * addDay);

  if(next==="next"){
    beginDateTime = beginDateTime+(86400000 * 7)
    endDateTime = endDateTime+(86400000 * 7)
  }
  beginDate = new Date(beginDateTime);
  endDate = new Date(endDateTime);
  return [beginDate,endDate]
}


export function getTime (type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

export function debounce (func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔last小于设定时间间隔wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

export function deepClone (source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'shallowClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  for (const keys in source) {
    if (source.hasOwnProperty(keys)) {
      if (source[keys] && typeof source[keys] === 'object') {
        targetObj[keys] = source[keys].constructor === Array ? [] : {}
        targetObj[keys] = deepClone(source[keys])
      } else {
        targetObj[keys] = source[keys]
      }
    }
  }
  return targetObj
}

function getMoney (s, n) {
  n = n > 0 && n <= 20 ? n : 2
  s = parseFloat((s + '').replace(/[^\d.-]/g, '')).toFixed(n) + ''
  let l = s.split('.')[0].split('').reverse()
  let r = s.split('.')[1]
  let t = ''
  for (let i = 0; i < l.length; i++) {
    t += l[i] + ((i + 1) % 3 === 0 && (i + 1) !== l.length ? ',' : '')
  }
  return t.split('').reverse().join('') + '.' + r
}

export function moneyFormat (val, n) {
  if (typeof val !== 'undefined') {
    const money = val / 10000
    return getMoney(money, n)
  }
}

export function numFixed (val) {
  const n = 2
  if (typeof val !== 'undefined') {
    const money = val / 10000
    const num = Number(money)
    return num.toFixed(n)
  }
}


export function createMD5 (pwd) {
  pwd = md5(pwd)
  return pwd
}

export function deleteEmptyProp(object){
  for (let i in object) {
    let value = object[i];
    if (typeof value === 'object') {
      if (Array.isArray(value)) {
        if (value.length == 0) {
          delete object[i];
          continue;
        }
      }
      this.deleteEmptyProperty(value);
      if (this.isEmpty(value)) {
        delete object[i];
      }
    } else {
      if (value === '' || value === null || value === undefined) {
        delete object[i];
      }
    }
  }
  return object
}


function isEmpty(object) {
  for  (let name in object) {
    return false;
  }
  return true;
}

/**
 * 移除数组元素  全部移除
 * @param arr
 * @param item
 * @returns {*}
 */
export function removeItem(arr,item){
  if(arr){
    let index = arr.indexOf(item);
    while(index>-1){
      arr.splice(index, 1);
      index = arr.indexOf(item);
    }
  }
  return arr
}

export function isValidIP(ip)
{
  // "^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\."
  //
  // +"(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\."
  //
  // +"(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\."
  //
  // +"(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)$"
  // let reg =  x
  let reg1=  /^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])\.((1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.){2}(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)$/
  return reg1.test(ip);
}


export function addDay(date,days) {
  if(typeof date === 'object'){
    let time = date.getTime()+days*24*3600*1000
    return new Date(time)
  }
}
